<template>
  <div class="gallery-container">
    <!-- 有context参数才渲染图片，避免undefined错误 -->
    <div class="image-grid single-item-grid" v-if="context">
      <div class="image-card">
        <img
          :src="imageUrl"
          :alt="context"
          class="item-image"
          @error="handleImageError"
        >
      </div>
    </div>

    <!-- 无参数时显示提示 -->
    <div class="no-context" v-else>
      未指定图片参数，请检查URL是否包含 ?context=xxx
    </div>

    <!-- 显示当前参数 -->
    <div class="pagination-controls" style="margin-top: 2rem;">
      <span class="page-info">
        当前图片: {{ context || '未指定' }}
      </span>
    </div>
  </div>
</template>

<script>
// Vue2 用 Options API，无需 <script setup>
export default {
  name: 'MainBox',
  computed: {
    // 从路由查询参数中获取context（Vue2 通过 this.$route 访问路由）
    context() {
      // 确保返回字符串，避免undefined
      return this.$route.query.context || '';
    },
    // 计算图片URL
    imageUrl() {
      if (this.context) {
        return `http://localhost:8080/project/image/${this.context}`;
      }
      return ''; // 空字符串避免无效请求
    }
  },
  methods: {
    // 图片加载错误处理
    handleImageError(e) {
      e.target.src = 'https://picsum.photos/200/200?grayscale';
      e.target.alt = '图片加载失败';
    }
  }
};
</script>

<style scoped>
/* 样式保持不变 */
.gallery-container {
  max-width: 400px;
  margin: 2rem auto;
  padding: 0 1rem;
  font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
}

.single-item-grid {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-bottom: 0;
}

.image-card {
  background-color: #ffffff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  overflow: hidden;
  transition: transform 0.3s ease, box-shadow 0.3s ease;
  width: 100%;
  aspect-ratio: 1 / 1;
  display: flex;
  align-items: stretch;
  justify-content: stretch;
}

.image-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 16px rgba(0, 0, 0, 0.12);
}

.item-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.5s ease;
  display: block;
}

.image-card:hover .item-image {
  transform: scale(1.05);
}

.pagination-controls {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 1.5rem;
}

.page-info {
  color: #4a5568;
  font-size: 1rem;
  font-weight: 500;
}

.no-context {
  text-align: center;
  padding: 2rem;
  color: #666;
  background-color: #f9f9f9;
  border-radius: 8px;
}
</style>
